package com.ssy.lingxi.contract.utils;

import cn.hutool.core.util.URLUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.URL;

/**
 * 文件工具类
 * @author yzc
 * @version 2.0.0
 * @date 2020/9/21
 */
public class FileUtils {

    private final static Logger log = LoggerFactory.getLogger(FileUtils.class);

    private FileUtils(){

    }

    /**
     * 根据url下载文件
     * @param fileUrl 文件地址
     * @return 文件字节
     */
    public static byte[] fileDownload(String fileUrl) {
        // 获取合同模板文件信息
        InputStream pdfis;
        try {
            URL url = URLUtil.toUrlForHttp(URLUtil.decode(fileUrl));
            pdfis = url.openStream();
        } catch (Exception e) {
            log.error("根据url下载文件失败", e);
            return new byte[0];
        }

        byte[] bytes;
        try (
                BufferedInputStream bis = new BufferedInputStream(pdfis)
        ) {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int length;
            byte[] buffer = new byte[1024];
            while ((length = bis.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }

            bytes = baos.toByteArray();
        } catch (Exception e) {
            log.error("根据url下载文件失败", e);
            return new byte[0];
        }

        return bytes;
    }

    /**
     * 构建文件请求类
     * @param bytes 文件字节
     * @param suffix 文件扩展名
     * @return
     */
    public static MultipartFile createMultipartFile(byte[] bytes, String suffix) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("file", "text/plain", true, "tempFile." + suffix);
        MultipartFile multipartFile;
        try (
                OutputStream outputStream = item.getOutputStream()
        ) {
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        multipartFile = new CommonsMultipartFile(item);
        return multipartFile;
    }

}
